package com.gentle.aspect;

import com.gentle.annotation.LockAnnotation;
import org.apache.curator.framework.recipes.locks.InterProcessMutex;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;


/**
 * 分布式锁注解
 * @author Gentle
 * @date 2019/05/30 : 17:48
 */
@Aspect
@Order(5)
@Component
public class LockIntercept {

    @Autowired
    private InterProcessMutex interProcessMutex;


    @Around("@annotation(lockAnnotation)")
    public void lockHandler(ProceedingJoinPoint joinPoint, LockAnnotation lockAnnotation ){

        boolean acquire=false;
        try {
            acquire  = interProcessMutex.acquire(lockAnnotation.time(), lockAnnotation.util());
            if (acquire){
                Object proceed = joinPoint.proceed();
            }
        } catch (Throwable throwable) {
            throwable.printStackTrace();
        }finally {
            if (acquire){
                try {
                    interProcessMutex.release();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }
    }




}
